<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="服务名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入服务名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类名称" prop="categoryName">
        <el-input
          v-model="queryParams.categoryName"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商户名称" prop="merchantName">
        <el-input
          v-model="queryParams.merchantName"
          placeholder="请输入商户名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:manage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:manage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:manage:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:manage:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="manageList" 
      @selection-change="handleSelectionChange"
      :row-style="{height: '50px'}"
      :cell-style="{padding: '5px'}"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="服务编号" align="center" prop="serviceNo" />
      <el-table-column label="服务名称" align="center" prop="name" />
      <el-table-column label="分类名称" align="center" prop="categoryName" />
      <el-table-column label="商户名称" align="center" prop="merchantName" />
      <el-table-column label="服务描述" align="left" prop="description" min-width="200" class-name="description-column">
        <template #default="scope">
          <div class="description-container">
            {{ scope.row.description }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="原价" align="center" prop="basePrice" />
      <el-table-column label="现价" align="center" prop="nowPrice" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:manage:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:manage:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改服务管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="manageRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="服务编号" prop="serviceNo">
          <el-input v-model="form.serviceNo" placeholder="请输入服务编号" :disabled="title.indexOf('修改') !== -1" />
        </el-form-item>
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入服务名称" />
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryName">
          <el-select v-model="form.categoryName" placeholder="请选择分类" clearable filterable style="width: 100%">
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商户名称" prop="merchantName">
          <el-select v-model="form.merchantName" placeholder="请选择商户名称" clearable filterable style="width: 100%">
            <el-option
              v-for="item in merchantOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入服务描述" />
        </el-form-item>
        <el-form-item label="原价" prop="basePrice">
          <el-input v-model="form.basePrice" placeholder="请输入原价" type="number" />
        </el-form-item>
        <el-form-item label="现价" prop="nowPrice">
          <el-input v-model="form.nowPrice" placeholder="请输入现价" type="number" />
        </el-form-item>
        <el-form-item label="服务图片" prop="img">
          <el-upload
            class="avatar-uploader"
            :action="uploadImgUrl"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="form.img" :src="form.img" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Manage">
import { listManage, getManage, delManage, addManage, updateManage, listMerchants, listServiceCategories } from "@/api/manage/manage"
import { ref, reactive, toRefs, getCurrentInstance, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'

const { proxy } = getCurrentInstance()
const router = useRouter()

// 上传图片相关变量
const uploadImgUrl = import.meta.env.VITE_APP_BASE_API + "/manage/manage/upload" // 上传的图片服务器地址
const headers = computed(() => {
  return { Authorization: "Bearer " + getToken() }
})

// 商户选项
const merchantOptions = ref([])
// 服务分类选项
const categoryOptions = ref([])

// 加载商户列表
function loadMerchantOptions() {
  listMerchants().then(response => {
    if (response.code === 200) {
      // 将返回的字符串数组转换为下拉框所需的对象数组格式
      merchantOptions.value = response.rows.map(item => {
        return {
          value: item,
          label: item
        }
      })
    } else {
      proxy.$modal.msgError(response.msg || '获取商户列表失败')
      // 加载失败时使用默认数据
      merchantOptions.value = [
        { value: '兔师傅汽车美容', label: '兔师傅汽车美容' },
        { value: '车享家汽车服务', label: '车享家汽车服务' },
        { value: '车仆汽车服务', label: '车仆汽车服务' }
      ]
    }
  }).catch(err => {
    console.error('获取商户列表出错:', err)
    // 加载失败时使用默认数据
    merchantOptions.value = [
      { value: '兔师傅汽车美容', label: '兔师傅汽车美容' },
      { value: '车享家汽车服务', label: '车享家汽车服务' },
      { value: '车仆汽车服务', label: '车仆汽车服务' }
    ]
  })
}

// 加载服务类别列表
function loadCategoryOptions() {
  listServiceCategories().then(response => {
    if (response.code === 200) {
      // 将返回的字符串数组转换为下拉框所需的对象数组格式
      categoryOptions.value = response.rows.map(item => {
        return {
          value: item,
          label: item
        }
      })
    } else {
      proxy.$modal.msgError(response.msg || '获取服务类别列表失败')
      // 加载失败时使用默认数据
      categoryOptions.value = [
        { value: '车辆维修', label: '车辆维修' },
        { value: '汽车美容', label: '汽车美容' },
        { value: '汽车保养', label: '汽车保养' }
      ]
    }
  }).catch(err => {
    console.error('获取服务类别列表出错:', err)
    // 加载失败时使用默认数据
    categoryOptions.value = [
      { value: '车辆维修', label: '车辆维修' },
      { value: '汽车美容', label: '汽车美容' },
      { value: '汽车保养', label: '汽车保养' }
    ]
  })
}

const manageList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    categoryName: null,
    merchantName: null,
  },
  rules: {
    serviceNo: [
      { required: true, message: "服务编号不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "服务名称不能为空", trigger: "blur" }
    ],
    categoryName: [
      { required: true, message: "分类名称不能为空", trigger: "blur" }
    ],
    merchantName: [
      { required: true, message: "商户名称不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

// 上传图片前的校验
function beforeUpload(file) {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    proxy.$modal.msgError('上传图片只能是JPG或PNG格式!')
    return false
  }
  if (!isLt2M) {
    proxy.$modal.msgError('上传图片大小不能超过2MB!')
    return false
  }
  return true
}

// 图片上传成功处理
function handleUploadSuccess(res, file) {
  if (res.code === 0) {
    form.value.img = res.data // 后端返回的是 { code: 0, message: "success", data: "图片URL" }
    proxy.$modal.msgSuccess("图片上传成功")
  } else {
    proxy.$modal.msgError("图片上传失败: " + (res.message || "未知错误"))
  }
}

/** 查询服务管理列表 */
function getList() {
  loading.value = true
  listManage(queryParams.value).then(response => {
    // 确保每条记录都有id字段，如果没有则使用serviceNo作为后备
    manageList.value = response.rows.map(item => {
      if (!item.id) {
        item.id = item.serviceNo;
      }
      return item;
    });
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    serviceNo: null,
    name: null,
    categoryName: null,
    merchantName: null,
    description: null,
    basePrice: null,
    nowPrice: null,
    img: null,
    createTime: null
  }
  proxy.resetForm("manageRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  router.push('/manage/add/index');
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getManage(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改服务管理"
    // 确保商户和分类选项已加载
    if (merchantOptions.value.length === 0) {
      loadMerchantOptions()
    }
    if (categoryOptions.value.length === 0) {
      loadCategoryOptions()
    }
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["manageRef"].validate(valid => {
    if (valid) {
      if (form.value.serviceNo != null) {
        updateManage(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addManage(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除服务"' + (row.name || '') + '"？').then(function() {
    return delManage(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/manage/export', {
    ...queryParams.value
  }, `manage_${new Date().getTime()}.xlsx`)
}

/** 格式化日期时间 */
function formatDateTime(dateTimeString) {
  if (!dateTimeString) {
    return '';
  }
  
  // 处理ISO格式的日期时间字符串
  const date = new Date(dateTimeString);
  
  // 格式化为 YYYY-MM-DD HH:MM:SS
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 页面挂载时加载数据
onMounted(() => {
  // 加载商户和服务类别数据
  loadMerchantOptions()
  loadCategoryOptions()
  getList()
})

</script>

<style scoped>
/* 设置服务描述列的样式，允许更多内容展示 */
.el-table :deep(.el-table__row) td:nth-child(6) {
  max-height: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

/* 当内容过长时显示省略号 */
.el-table :deep(.cell) {
  white-space: normal;
  word-break: break-all;
}

/* 服务描述列样式 */
.description-column {
  text-align: left !important;
}

.description-container {
  max-width: 100%;
  overflow-x: auto;
  padding: 5px 0;
  max-height: 80px;
  text-align: left;
}

/* 设置水平滚动条样式 */
.description-container::-webkit-scrollbar {
  height: 6px;
}

.description-container::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 3px;
}

.description-container::-webkit-scrollbar-track {
  background-color: #f0f2f5;
}

/* 图片上传样式 */
.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}
</style>
